package com.fxust.common;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.Properties;

/**
 * @auto johnking
 * @create 2017-12-17 上午11:26
 **/
public class ConnectionPoolManager {

    private static final Logger logger = LoggerFactory.getLogger(ConnectionPoolManager.class);

    private static ConnectionPoolManager connectionPool = null;
    private static DruidDataSource druidDataSource = null;

    /*
     * 数据库静态初始化
     */
    static{
        Properties properties = PropertiesHandler.loadPropertiesConfig();
        System.out.println(properties);
        try {
            druidDataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            logger.error("获取配置源错误",e);
        }
    }
    private ConnectionPoolManager() {}

    /**
     * 单例模式-保证只有一个连接实例
     * @author fgq 2017年8月8日 下午2:05:07
     * @return
     */
    public static synchronized ConnectionPoolManager getInstance(){

        if(null == connectionPool){
            connectionPool = new ConnectionPoolManager();
        }
        return connectionPool;
    }

    /**
     * 获取连接池对象
     * @author fgq 2017年8月8日 下午2:06:04
     * @return
     * @throws SQLException
     */
    public DruidPooledConnection getConnection() throws SQLException {
        return druidDataSource.getConnection();
    }
}
